package com.offdissys.common.utils.bean;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhangHaiWen
 * @title: BeanUtils
 * @projectName parent
 * @description: Bean工具类
 * @date 2022/3/714:53
 */
public class BeanUtils {

    /**
     * bean转为Map
     * @param object
     * @return
     */
    public static Map<String,Object> bean2Map(Object object){
        if(object == null){
            return null;
        }
        Map hashMap = new HashMap();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String name = propertyDescriptor.getName();
                if (name.compareToIgnoreCase("class") == 0) {
                    continue;
                }
                Method readMethod = propertyDescriptor.getReadMethod();
                Object value = readMethod.invoke(object);
                hashMap.put(name,value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hashMap;
    }

    /**
     * map转化为Bean
     * @param map
     * @param beanClass
     * @return
     */
    public static Object map2Bean(Map<String, Object> map, Class<?> beanClass) {
        if (map == null){
            return null;
        }
        try {
            Object obj = beanClass.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                Method setter = property.getWriteMethod();
                if (setter != null) {
                    setter.invoke(obj, map.get(property.getName()));
                }
            }
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
